package cn.iocoder.yudao.module.system.controller.admin.wishlist;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.controller.admin.wishlist.vo.*;
import cn.iocoder.yudao.module.system.convert.wishlist.UserWishListConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.wishlist.UserWishListDO;
import cn.iocoder.yudao.module.system.service.wishlist.UserWishListService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户志愿表 Controller
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 用户志愿表")
@RestController
@RequestMapping("/system/user-wish-list")
@Validated
@Slf4j
public class UserWishListController {

    @Resource
    private UserWishListService userWishListService;

    @PostMapping("/create")
    @Operation(summary = "创建用户志愿表")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:create')")
    public CommonResult<Long> createUserWishList(@Valid @RequestBody UserWishListCreateReqVO createReqVO) {
        return success(userWishListService.createUserWishList(createReqVO, getLoginUserId()));
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户志愿表")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:update')")
    public CommonResult<Boolean> updateUserWishList(@Valid @RequestBody UserWishListUpdateReqVO updateReqVO) {
        userWishListService.updateUserWishList(updateReqVO, getLoginUserId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户志愿表")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:delete')")
    public CommonResult<Boolean> deleteUserWishList(@RequestParam("id") Long id) {
        userWishListService.deleteUserWishList(id, getLoginUserId());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户志愿表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<UserWishListRespVO> getUserWishList(@RequestParam("id") Long id) {
        UserWishListDO userWishList = userWishListService.getUserWishList(id, getLoginUserId());
        return success(BeanUtils.toBean(userWishList, UserWishListRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户志愿表分页")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<PageResult<UserWishListRespVO>> getUserWishListPage(@Valid UserWishListPageReqVO pageReqVO) {
        // 设置当前用户ID，确保只能查看自己的志愿
        pageReqVO.setUserId(getLoginUserId());
        PageResult<UserWishListDO> pageResult = userWishListService.getUserWishListPage(pageReqVO);
        return success(UserWishListConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/list")
    @Operation(summary = "获得用户的所有志愿表")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<List<UserWishListRespVO>> getUserWishListByUserId() {
        List<UserWishListDO> list = userWishListService.getUserWishListByUserId(getLoginUserId());
        return success(UserWishListConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-by-type")
    @Operation(summary = "获得用户指定类型的志愿表")
    @Parameter(name = "wishType", description = "志愿类型", required = true, example = "rush")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<List<UserWishListRespVO>> getUserWishListByUserIdAndWishType(@RequestParam("wishType") String wishType) {
        List<UserWishListDO> list = userWishListService.getUserWishListByUserIdAndWishType(getLoginUserId(), wishType);
        return success(UserWishListConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/grouped")
    @Operation(summary = "获得用户志愿表（按类型分组）")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<Map<String, List<UserWishListRespVO>>> getUserWishListGrouped() {
        List<UserWishListDO> list = userWishListService.getUserWishListByUserId(getLoginUserId());
        Map<String, List<UserWishListRespVO>> grouped = UserWishListConvert.INSTANCE.convertList(list)
                .stream()
                .collect(Collectors.groupingBy(UserWishListRespVO::getWishType));
        return success(grouped);
    }

    @PostMapping("/update-order")
    @Operation(summary = "更新志愿顺序")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:update')")
    public CommonResult<Boolean> updateWishOrder(@RequestParam("wishType") String wishType,
                                                  @RequestBody List<Long> wishListIds) {
        userWishListService.updateWishOrder(getLoginUserId(), wishType, wishListIds);
        return success(true);
    }

    @GetMapping("/check-exists")
    @Operation(summary = "检查专业是否已添加到志愿表")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<Boolean> checkWishListExists(@RequestParam("schoolUuid") String schoolUuid,
                                                      @RequestParam("majorName") String majorName,
                                                      @RequestParam("year") Integer year) {
        boolean exists = userWishListService.isWishListExists(getLoginUserId(), schoolUuid, majorName, year);
        return success(exists);
    }

    @GetMapping("/count-by-type")
    @Operation(summary = "获取用户指定类型志愿的数量")
    @Parameter(name = "wishType", description = "志愿类型", required = true, example = "rush")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<Long> getWishListCountByUserIdAndWishType(@RequestParam("wishType") String wishType) {
        Long count = userWishListService.getWishListCountByUserIdAndWishType(getLoginUserId(), wishType);
        return success(count);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户志愿表 Excel")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:export')")
    public void exportUserWishListExcel(@Valid UserWishListPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        pageReqVO.setUserId(getLoginUserId());
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<UserWishListDO> list = userWishListService.getUserWishListPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "用户志愿表.xls", "数据", UserWishListRespVO.class,
                UserWishListConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/export-file")
    @Operation(summary = "导出用户志愿表并返回下载链接")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:export')")
    public CommonResult<String> exportUserWishListFile(@Valid UserWishListPageReqVO pageReqVO) {
        return success(userWishListService.exportUserWishListToFile(pageReqVO, getLoginUserId()));
    }

    @GetMapping("/get-with-score")
    @Operation(summary = "获得用户志愿表（包含成绩信息）")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<UserWishListWithScoreRespVO> getUserWishListWithScore(@RequestParam("id") Long id) {
        UserWishListWithScoreRespVO wishList = userWishListService.getUserWishListWithScore(id, getLoginUserId());
        return success(wishList);
    }

    @GetMapping("/list-with-score")
    @Operation(summary = "获得用户的所有志愿表（包含成绩信息）")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<List<UserWishListWithScoreRespVO>> getUserWishListWithScoreByUserId() {
        List<UserWishListWithScoreRespVO> list = userWishListService.getUserWishListWithScoreByUserId(getLoginUserId());
        return success(list);
    }

    @GetMapping("/page-with-score")
    @Operation(summary = "获得用户志愿表分页（包含成绩信息）")
    @PreAuthorize("@ss.hasPermission('system:user-wish-list:query')")
    public CommonResult<PageResult<UserWishListWithScoreRespVO>> getUserWishListWithScorePage(@Valid UserWishListPageReqVO pageReqVO) {
        PageResult<UserWishListWithScoreRespVO> pageResult = userWishListService.getUserWishListWithScorePage(pageReqVO);
        return success(pageResult);
    }

}
